{% extends "base.html" %}

{% block title %}主机{% endblock %}

{% block head %}
{{ super() }}
<!-- DataTables -->
<link rel="stylesheet" href="/static/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css">
<!-- DataTables button -->
<link rel="stylesheet" href="/static/bower_components/fx/buttons.bootstrap.min.css">
<!-- DataTables searchPanes -->
<link rel="stylesheet" href="/static/bower_components/fx/searchPanes.bootstrap.min.css">
<link rel="stylesheet" href="/static/bower_components/fx/select.bootstrap.min.css">
{% endblock %}

{% block content %}
<!-- 页面头 -->
<section class="content-header">
  <!--头部标题-->
  <h1>
    主机
    <!--    <small>advanced tables</small>-->
  </h1>
  <!--面包屑-->
  <ol class="breadcrumb">
    <li><a href="/"><i class="fa fa-home"></i> 主页</a></li>
    <li>资产管理</li>
    <li class="active">主机</li>
  </ol>
</section>

<!-- 页面内容 -->
<section class="content">
  <div class="row">
    <div class="col-xs-12">
      <!--表格1-->
      <div class="box">
        <div class="box-header">
          <!--          <h3 class="box-title">公共平台</h3>-->
        </div>
        <div class="box-body table-responsive">
          <table id="example" class="table  table-condensed table-bordered table-hover"
                 style="font-size: 90%;width:100%">
            <thead>
            <tr>
              <th style="text-align: center">内网IP</th>
              <th style="text-align: center">外网IP</th>
              <th style="text-align: center">项目</th>
              <th style="text-align: center">归属方</th>
              <th style="text-align: center">名称</th>
              <th style="text-align: center">区域</th>
              <th style="text-align: center">云厂商</th>
              <th style="text-align: center">网络区域</th>
              <th style="text-align: center">产品线</th>
              <th style="text-align: center">环境</th>
              <th style="text-align: center">实例ID</th>
              <th style="text-align: center">备注</th>
              <th style="text-align: center">状态</th>
              <th style="text-align: center">操作系统</th>
              <th style="text-align: center">架构</th>
              <th style="text-align: center">CPU</th>
              <th style="text-align: center">内存</th>
              <th style="text-align: center">系统盘</th>
              <th style="text-align: center">数据盘</th>
              <th style="text-align: center">维护人</th>
              <th style="text-align: center">电话</th>
              <th>ssh端口</th>
              <th>ssh账户</th>
              <th>ssh密码</th>
            </tr>
            </thead>
            <tbody>

            </tbody>
          </table>

        </div>
        <!-- /.box-body -->
      </div>
      <!-- /.box -->

    </div>
    <!-- /.col -->
  </div>
  <!-- /.row -->
</section>
<!-- /.页面内容 -->


<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
          aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">导入Excel数据</h4>
      </div>
      <div class="modal-body">
        <!--隐藏字段-->
        <input class="hidden" type="text" id="filename" value="">
        <p>1. <a href="/static/cmdb_template.xlsx">下载Excel模板</a></p>
        <p>2. 将资产统计到Excel中，点击下方按钮上传文件</p>
        <input type="file" id="uploadFile">&nbsp;
        <p>3. 选择要导入的表单：</p>
        <select class="form-control" disabled="disabled" id="selectSheet">
          <!--          <option>&#45;&#45;请选择表单&#45;&#45;</option>-->
        </select>
        &nbsp;
        <div class="callout">
          <p><strong>导入规则说明：</strong></p>
          <ul class="list-unstyled">
            <li>a. 由 <span class="text-red">项目名 + 资源主字段</span>（表格左侧第一列）表示一个唯一的资产。例如：</li>
            <ul>
              <li>主机：项目名 + 内网IP</li>
              <li>数据库：项目名 + 内网IP</li>
              <li>负载均衡：项目名 + IP</li>
              <li>对象存储：项目名 + Bucket名</li>
              <li>Redis：项目名 + 内网IP</li>
              <li>业务：项目名 + 内网地址</li>
            </ul>
            <li>b. 若导入的唯一资产在cmdb中不存在，则新增</li>
            <li>c. 若导入的唯一资产在cmdb中已存在，则更新</li>
            <li>d. 若导入的唯一资产deleted字段值为1，则删除</li>
          </ul>

        </div>

      </div>

      <div class="modal-footer">
        <!--        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>-->

        <button id="importBtn" type="button" class="btn btn-success" disabled="disabled">导入数据</button>
        <div id="loading" style="display: none"><p><i class='fa fa-spin fa-spinner'></i> 导入中...</p></div>

      </div>
    </div>
  </div>
</div>


{% endblock %}


{% block script %}
<!-- DataTables -->
<script src="/static/bower_components/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="/static/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
<!-- DataTables buttons-->
<script src="/static/bower_components/fx/dataTables.buttons.min.js"></script>
<script src="/static/bower_components/fx/buttons.bootstrap.min.js"></script>
<script src="/static/bower_components/fx/jszip.min.js"></script>
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>-->

<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>-->
<script src="/static/bower_components/fx/buttons.html5.min.js"></script>
<!--<script src="https://cdn.datatables.net/buttons/2.2.2/js/buttons.print.min.js"></script>-->
<script src="/static/bower_components/fx/buttons.colVis.min.js"></script>

<!-- DataTables searchPanes-->
<script src="/static/bower_components/fx/dataTables.searchPanes.min.js"></script>
<script src="/static/bower_components/fx/searchPanes.bootstrap.min.js"></script>
<script src="/static/bower_components/fx/dataTables.select.min.js"></script>

<!-- Page specific script -->
<script>
    $.fn.dataTable.ext.buttons.upload = {
        text: "<i class='fa fa-upload'></i>",
        action: function (e, dt, node, config) {
            // alert('导入excel')
            $('#myModal').modal()
        }
    };

    $(document).ready(function () {
        var table = $('#example').DataTable({
            ajax: '/api/v1/cmdb/host',
            columns: [
                {data: 'innerip'},
                {data: 'outerip'},
                {data: 'project'},
                {data: 'owner'},
                {data: 'name'},
                {data: 'area'},
                {data: 'cloud_vendor'},
                {data: 'net_zone'},
                {data: 'product'},
                {data: 'env'},
                {data: 'ins_id'},
                {data: 'comment'},
                {data: 'status'},
                {data: 'os'},
                {data: 'arch'},
                {data: 'cpu'},
                {data: 'mem'},
                {data: 'sysdisk'},
                {data: 'datadisk'},
                {data: 'operator'},
                {data: 'phone'},
                {data: 'ssh_port'},
                {data: 'ssh_user'},
                {data: 'ssh_password'},
            ],
            order: [[2, 'asc'], [0, 'asc']],
            processing: true,
            language: {
                "url": "/static/language.json"
            },
            lengthChange: false,
            searchPanes: {
                initCollapsed: true,
                // cascadePanes: true
                columns: [2, 5, 7, 9,]
            },
            scrollX: true,
            responsive: true,
            autoWidth: true,
            stateSave: true,
            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
            buttons: [
                'pageLength',
                {
                    extend: 'colvis',
                    collectionTitle: '显示/隐藏列'
                },
                'excel',
                'upload',
            ],
            columnDefs: [
                {
                    "targets": [3, 6, 7,8, 10, 11, 12, 14, 19, 20],
                    "visible": false,
                }
            ],
            initComplete: function () {
                table.buttons().container().appendTo('#example_wrapper .col-sm-6:eq(0)')
                table.searchPanes.container().prependTo(table.table().container());
                table.searchPanes.resizePanes();
                table.columns.adjust().draw();
            }
        });

        // 根据URL的search参数，自动搜索
        let searchString = getQueryString('search')
        if (searchString !== '') {
            console.log(searchString)
            table.search(searchString);
            table.draw();
        }

        // 解决sidebar toogle之后，datatables标题行错位问题
        $('.sidebar-toggle').click(function () {
            $('.dataTables_scrollHeadInner').css('width', '100%');
            $('#example').css('width', '100%');
            setTimeout(function () {
                table.columns.adjust().draw();
            }, 400);
        });

        //自动上传excel
        $('#uploadFile').change(function () {
            if ($(this).val() != '') {
                // alert('uploading')
                upload(this)
            }


        })
    });


    function upload(ele) {
        var formData = new FormData();
        var name = $(ele).val();
        var file = $(ele)[0].files[0];
        formData.append('file', file);
        formData.append('name', name);
        $.ajax({
            url: "/api/v1/cmdb/upload",
            type: "POST",
            data: formData,
            contentType: false,
            cache: false,
            processData: false,
            success: function (data) {
                console.log(data);
                // alert(data)
                // $('#selectSheet').find('option').remove()
                for (let i in data.sheets_name) {
                    $('#selectSheet').append('<option value="' + data.sheets_name[i] + '">' + data.sheets_name[i] + '</option>')
                }
                $('#selectSheet').removeAttr('disabled');
                $('#importBtn').removeAttr('disabled');
                $('#filename').val(data.filename)
            }
        });
    }

    $('#importBtn').click(function () {
        $('#importBtn').attr('disabled', 'disabled')
        $('#loading').show()
        $.ajax({
            url: "/api/v1/cmdb/update",
            headers: {Accept: "application/json; charset=utf-8"},
            type: "POST",
            data: {
                type: 'host',
                filename: $('#filename').val(),
                sheet_name: $('#selectSheet').val(),
            },
            success: function (data) {
                console.log(data)
                let t = "导入结果：新增" + data.insert_count + "行，更新" + data.change_count + "行，忽略" + data.ignore_count + "行"
                alert(t)
                $('#loading').text(t)
                // $('#myModal').modal('hide')
            }
        })
    })

</script>
{% endblock%}